package com.fengniaoxls.fengniaonewretail.jpush.voice.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.fengniaoxls.fengniaonewretail.FloatWindow;
import com.fengniaoxls.fengniaonewretail.R;
import com.freak.httphelper.log.LogUtil;


/**
 * @author Freak
 * @date 2019/7/24.
 */
public class KeepLiveManager {

    /**
     * 前台进程的NotificationId
     */
    private final static int GRAY_SERVICE_ID = 1001;

    /**
     * Channel ID 必须保证唯一
     */
    private static final String CHANNEL_ID = "com.fengniaoxls.fengniaonewretail";

    /**
     * 单例模式
     */
    private static KeepLiveManager instance = new KeepLiveManager();

    /**
     * 1像素的透明Activity
     */
    private PixelActivity activity;

    /**
     * 监听锁屏/解锁的广播（必须动态注册）
     */
    private LockReceiver lockReceiver;


    public static KeepLiveManager getInstance() {
        return instance;
    }

    /**
     * 传入1像素的透明Activity实例
     *
     * @param activity
     */
    public void setKeepLiveActivity(PixelActivity activity) {
        this.activity = activity;
    }

    /**
     * 注册锁屏/解锁广播
     *
     * @param context
     */
    public void registerReceiver(Context context) {
        Log.e("TAG", "锁屏注册广播");
        lockReceiver = new LockReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        context.registerReceiver(lockReceiver, filter);
    }

    /**
     * 注销锁屏/解锁广播
     *
     * @param context
     */
    public void unRegisterReceiver(Context context) {
        if (lockReceiver != null) {
            context.unregisterReceiver(lockReceiver);
        }
    }

    /**
     * 设置服务为前台服务
     *
     * @param service
     */
    public void setServiceForeground(Service service) {
        //设置service为前台服务，提高优先级
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            //Android4.3以下 ，此方法能有效隐藏Notification上的图标
            service.startForeground(GRAY_SERVICE_ID, new Notification());
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
            //Android4.3 - Android7.0，此方法能有效隐藏Notification上的图标
            Intent innerIntent = new Intent(service, GrayInnerService.class);
            service.startService(innerIntent);
            service.startForeground(GRAY_SERVICE_ID, new Notification());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //
            //Android7.1 google修复了此漏洞，暂无解决方法（现状：Android7.1以上app启动后通知栏会出现一条"正在运行"的通知消息）
            //设定的通知渠道名称
            String channelName = "收款语音播报";
            String appName = service.getString(R.string.app_name);
            //设置通知的重要程度
            int importance = NotificationManager.IMPORTANCE_LOW;
            //构建通知渠道
            NotificationChannel channel = null;
            channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
//        channel.setDescription(description);
            //在创建的通知渠道上发送通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(service, CHANNEL_ID);
            builder.setSmallIcon(R.mipmap.ic_logo) //设置通知图标
                    .setContentTitle(appName + "正在运行")//设置通知标题
//                .setContentText("语音播报")//设置通知内容
                    .setAutoCancel(true) //用户触摸时，自动关闭
                    .setOngoing(true);//设置处于运行状态
            //向系统注册通知渠道，注册后不能改变重要性以及其他通知行为
            NotificationManager notificationManager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(channel);
            //将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID
            service.startForeground(GRAY_SERVICE_ID, builder.build());
        }
    }

    private void startLiveActivity(Context context) {
        LogUtil.e("开启");
        Intent intent = new Intent(context, PixelActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private void destroyLiveActivity() {
        if (activity != null) {
            activity.finish();
        }
    }

    class LockReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_SCREEN_OFF:
                    Log.e("TAG", "锁屏  锁屏");

//                    startLiveActivity(context);
                    FloatWindow.getInstance(context).addFloatWindow();
                    break;
                case Intent.ACTION_USER_PRESENT:
                    Log.e("TAG", "锁屏  解锁");
//                    destroyLiveActivity();
                    FloatWindow.getInstance(context).removeFloatWindow();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 辅助Service
     */
    public static class GrayInnerService extends Service {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(GRAY_SERVICE_ID, new Notification());
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

}
